package org.weiyonghua.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.weiyonghua.dao.BaseDao;
import org.weiyonghua.domain.User;
import org.weiyonghua.service.UserService;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by weiyonghua on 2017/3/23.
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    @Qualifier("primaryJdbcTemplate")
    private JdbcTemplate jdbcTemplate;
    @Autowired
    BaseDao<User> userBaseDao;

    public void saveUser(User user) {
        log.info("新增用户：{}", user.toString());
        jdbcTemplate.update("INSERT INTO `t_user` (`username`, `password`) VALUES (?, ?)", user.getUsername(), user.getPassword());
    }

    public User getUserByUsername(String username) {
        User user = userBaseDao.queryForObjectNullable("SELECT * FROM t_user WHERE username=?", new RowMapper<User>() {
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                Long userId = resultSet.getLong("id");
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                return User.builder().userId(userId).username(username).password(password).build();
            }
        }, username);
        log.info("根据用户名查询用户result：{}", null == user ? "null" : user.toString());
        return user;
    }

    public void deleteByUsername(String username) {
        log.info("删除用户：{}", username);
        jdbcTemplate.update("DELETE FROM t_user where username=?", username);
    }

    public List<User> listUser() {
        List<User> users = jdbcTemplate.queryForList("SELECT * FROM  t_user", User.class);
        log.info("list全部用户size：{}", users.size());
        return users;
    }

    public void deleteAllUsers() {
        log.info("删除全部用户");
        jdbcTemplate.update("DELETE FROM t_user");
    }
}
